<template>
	<view class="order-box">
		<view class="tabs">
			<v-tabs :tabs="tabs" @changeType="changeType" :selected="activeTab" />
		</view>
		<view class="shop-box" v-if='list.length'>
			<view class="shop-list"  v-for="item in list" :key="item.orderId">
				<view class="shop-title-box" @click="link(`/page_mall/shop/shop?id=${item.shopOrderDetailsVoList[0].storeId}`)">
					<view class="shop-left">
						<img class="shop-avatar" :src="`${img_baseUrl}/statics/std/static/shop.png`" alt="" />
						<text class="shop-title">{{ item.shopOrderDetailsVoList[0].storeName }}</text>
					</view>
					<view v-if="item.orderStatus == '1'" class="order-status await">
						{{ item.orderStatus | orderStatusFilter }}
					</view>
					<view v-if="item.orderStatus == '2' || item.orderStatus == '7'" class="order-status paid">
						{{ item.orderStatus | orderStatusFilter }}
					</view>
					<view v-if="item.orderStatus == '4' || item.orderStatus == '3'" class="order-status cancel">
						{{ item.orderStatus | orderStatusFilter }}
					</view>
				</view>
				<view @click="link(`/page_my/order/detail?id=${item.orderId}`)">
					<view class="item" v-for="it in item.shopOrderDetailsVoList" :key="it.goodsId">
						<view class="left">
							<img class="avatar" :src="img_baseUrl + it.goodsPic" alt="" />
						</view>
						<view class="right">
							<view class="title">{{ it.goodsName }}</view>
							<view class="shop-desc">{{ it._goodsSpec }}</view>
							<view class="price-num-box">
								<view class="price">¥{{ it.unitPrice.toFixed(2) }}</view>
								<view class="num"> x {{ it.goodsCount }}</view>
							</view>
						</view>
					</view>
				</view>
				<view class="price-count-box">
					<text class="price-text">应付金额</text>
					<text class="price-num">¥{{ item.orderTotalPrice == 0 ? 0.00 : item.orderTotalPrice.toFixed(2) }}</text>
				</view>
				<view class="btn-box" v-if="item.orderStatus == '1'">
					<view class="order-btn cancel" @click="cancelOrder(item.orderId)"> 取消订单</view>
					<view class="order-btn pay" @click="link(`/page_my/order/detail?id=${item.orderId}`)"> 去支付</view>
				</view>
				<view class="btn-box" v-if="item.orderStatus == '2'">
					<view class="order-btn contact" @click="callPhone(item)"> 联系客服</view>
				</view>
				<view class="btn-box" v-if="item.orderStatus == '5'">
					<view class="btn-box">
						<view class="order-btn contact" @click="callPhone(item)"> 联系客服</view>
						<view class="order-btn view"> 查看快递单号</view>
					</view>
				</view>
				<view class="btn-box" v-if="item.orderStatus == '3'">
					<view class="order-btn cancel" @click="delOrder(item.orderId)"> 删除订单</view>
				</view>
			</view>
			
		</view>
		<view class="noData" v-else style="height: '100%'">
			<image :src="`${img_baseUrl}/statics/std/static/noData.png`"></image>
			<text>暂无数据</text>
		</view>
	</view>
</template>

<script>
	import vTabs from "@/components/tabs.vue";
	import requestPost, {
		requestGet
	} from "@/utils/request";
	import {
		ticketOrderStatus
	} from "@/utils/constant";

	export default {
		components: {
			vTabs
		},
		data() {
			return {
				img_baseUrl: process.env.VUE_APP_BASEURL_IMG_API,
				tabs: [{
						label: "",
						text: "全部",
					},
					{
						label: 1,
						text: "待支付",
					},
					{
						label: 2,
						text: "已支付",
					},
					{
						label: 5,
						text: "已发货",
					},
				],
				list: [],
				current: 1,
				activeTab: "",
				total: 0,
				loadAll: false, // 已加载全部
				keyId: 0,
				nowGet: null
			};
		},
		filters: {
			orderStatusFilter: function(value) {
				return ticketOrderStatus[value] || "null";
			},
		},
		onShow() {
			this._getList();
		},
		methods: {
			changeType(e) {
				this.activeTab = e.type;
				this.total = 0
				this.keyId = 0
				this.list = []
				this.current = 1
				if (this.nowGet) {
					this.nowGet.abort()
					this.nowGet = null
				}
				uni.showLoading({
					title: "加载中",
				});
				this._getList();
			},
			_getList() {
				console.log('开始进入到新的了')
				let _this = this
				this.nowGet = uni.request({
					url: process.env.VUE_APP_BASEURL_API + "/order/mobile/shop/list",
					data: {
						...(this.activeTab !== 0 ? { orderStatus: this.activeTab } : {}),
						pageNum: this.current,
						pageSize: 10,
					},
					header: {
						"content-type": "application/json;charset=UTF-8",
						Authorization: "Bearer " + uni.getStorageSync("X-Token"),
					},
					method: "GET",
					dataType: "json",
					success: (res) => {
						console.log('进入到新的请求这里了', res)
						this.$nextTick(() => {
							if (res.data.code === 200) {
								_this.total = res.data.total;
                res.data.rows.forEach((order) => {
                  order.shopOrderDetailsVoList.forEach((orderDetail) => {
                    if (orderDetail.goodsSpec) {
                      orderDetail.goodsSpec = JSON.parse(orderDetail.goodsSpec);
                    } else {
                      orderDetail.goodsSpec = [];
                    }
                    orderDetail._goodsSpec = orderDetail.goodsSpec.join("，");
                  });
                });
								_this.list =
									_this.current === 1 ? res.data.rows : _this.list.concat(res.data.rows);
								_this.keyId++;
								console.log('获取到新的数据了呢', _this.list)
							} else if(res.data.code === 401){
                _this.status401();
              } else {
								_this.list = [];
							}
							uni.hideLoading();
						})
						
					},
					fail: () => {
						_this.list = [];
						uni.hideLoading();
					}
				});
			},
      status401() {
        uni.showModal({
          title: "提示",
          content: "登录状态已过期，请重新登录",
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              uni.removeStorageSync("X-Token");
              uni.removeStorageSync("X-UserInfo");
              uni.navigateTo({
                url: "/pages/login/index",
              });
            } else if (res.cancel) {
              console.log("用户点击取消");
              uni.removeStorageSync("X-Token");
              uni.removeStorageSync("X-UserInfo");
            }
          },
        });
      },
			link(url) {
				uni.navigateTo({
					url,
				});
			},
			// 取消订单
			cancelOrder(id) {
				const _this = this;
				uni.showModal({
					title: "提示",
					content: "确定要取消该订单吗？",
					success: function(res) {
						if (res.confirm) {
							console.log("用户点击确定");
							uni.showLoading({
								title: "加载中",
							});
							requestPost(`/order/mobile/shop/cancel/${id}`, {},'','PUT').then((res) => {
								if (res.code === 200) {
									uni.showToast({
										title: "已取消",
										icon: "none"
									});
                  _this.current = 1;
									_this._getList();
								}
							});
						} else if (res.cancel) {
							console.log("用户点击取消");
						}
					},
				});
			},
			//     删除订单
			delOrder(id) {
				const _this = this;
				uni.showModal({
					title: "提示",
					content: "确定要删除该订单吗？",
					success: function(res) {
						if (res.confirm) {
							console.log("用户点击确定");
							requestPost(`/order/mobile/shop/${id}`,'','','DELETE').then((res) => {
								if (res.code === 200) {
									uni.showToast({
										title: "已删除",
										icon: "none"
									});
									uni.showLoading({
										title: "加载中",
									});
                  _this.current = 1;
									_this._getList();
								}
							});
						} else if (res.cancel) {
							console.log("用户点击取消");
						}
					},
				});
			},
			// 支付前获取订单详细
			getPayOrderInfo: function(orderId) {
				if (this.isSubmitting) return;
				this.isSubmitting = true;
				requestGet(`/order/order/payOrder/${orderId}`).then((res) => {
					if (res.code === 200) {
						//调用微信官方支付接口弹出付款界面,输入密码扣款
						wx.requestPayment({
							provider: "wxpay",
							timeStamp: String(res.data.timeStamp),
							nonceStr: res.data.nonceStr,
							package: res.data.package,
							signType: res.data.signType,
							paySign: res.data.paySign,
							success: function(res) {
								console.log("success:" + JSON.stringify(res));
								uni.navigateTo({
									url: "/page_index/ticket/result?state=1&id=orderId",
								});
							},
							fail: function(err) {
								console.log("fail:" + JSON.stringify(err));
								uni.navigateTo({
									url: "/page_index/ticket/result?state=0&id=orderId",
								});
							},
						});
						this.isSubmitting = false;
					}
				});
			},
			// 拨打电话
			callPhone(item) {
				requestGet(`/shop/mobile/store/${item.storeId}`, {}).then((res) => {
					if (res.code === 200 && res.data && res.data.phone && res.data.phone != '') {
						uni.makePhoneCall({
							phoneNumber: res.data.phone,
						});
					} else {
						uni.showToast({
							title: "暂无联系电话",
							icon: "none",
						});
						return;
					}
				});
			},
		},
		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom: function() {
			if (this.list?.length < this.total) {
				this.current = this.current + 1;
				this._getList();
			} else {
				this.loadAll = true;
			}
		},
	};
</script>

<style lang="scss">
	.order-box {
		background: #F5F7F6;
		min-height: 100vh;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
	}

	.shop-box {
		box-sizing: border-box;
		margin-top: 16rpx;
		padding: 0 32rpx;
	}

	.tabs {
		position: sticky;
		top: 0;
		padding: 12rpx 32rpx;
		background: #F5F7F6;

		.tab_contant {
			background: #F5F7F6 !important;
		}
	}

	.shop-list {
		background: #ffffff;
		border-radius: 24rpx 24rpx 24rpx 24rpx;
		padding: 24rpx;
		margin-bottom: 24rpx;
	}

	.shop-title-box {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding-bottom: 10rpx;
	}

	.shop-left {
		display: flex;
	}

	.shop-avatar {
		width: 40rpx;
		height: 40rpx;
		margin-right: 16rpx;
	}

	.shop-title {
		font-size: 28rpx;
		font-weight: 400;
		color: #87A198;
		line-height: 40rpx;
	}

	.order-status {
		font-size: 28rpx;
		font-weight: 700;
		line-height: 40rpx;

		&.await {
			color: #EE9802;
		}

		&.paid {
			color: rgba(0, 0, 0, 0.9);
		}

		&.delive {
			color: rgba(0, 0, 0, 0.9);
		}

		&.cancel {
			color: rgba(0, 0, 0, 0.3);
		}
	}

	.item {
		padding-top: 24rpx;
		display: flex;
		align-items: center;

		.left {
			width: 160rpx;
			height: 160rpx;
			margin-right: 24rpx;

			.avatar {
				width: 100%;
				height: 100%;
				border-radius: 16rpx 16rpx 16rpx 16rpx;
			}
		}

		.right {
			flex: 1;

			.title {
				font-size: 32rpx;
				font-weight: 400;
				color: rgba(0, 0, 0, 0.8);
				line-height: 44rpx;
				padding-bottom: 16rpx;
			}

			.shop-desc {
				display: inline-block;
				background: #F3F6F5;
				border-radius: 8rpx 8rpx 8rpx 8rpx;
				padding: 4rpx 8rpx;
				font-size: 24rpx;
				font-weight: 400;
				color: rgba(0,0,0,0.5);
				line-height: 32rpx;
				margin-bottom: 22rpx;
			}

			.price-num-box {
				display: flex;
				align-items: center;
				justify-content: space-between;
			}

			.price {
				font-size: 32rpx;
				font-weight: 700;
				color: rgba(0, 0, 0, 0.8);
				line-height: 34rpx;
			}

			.num {
				font-size: 32rpx;
				font-weight: 400;
				color: rgba(0, 0, 0, 0.7);
				line-height: 44rpx;
			}
		}
	}

	.price-count-box {
		padding-top: 40rpx;
		padding-bottom: 32rpx;
		display: flex;
		justify-content: space-between;

		.price-text {
			padding-right: 16rpx;
			font-size: 28rpx;
			font-weight: 400;
			color: rgba(0, 0, 0, 0.7);
			line-height: 40rpx;
		}

		.price-num {
			font-size: 32rpx;
			font-weight: 700;
			color: #ff7614;
			line-height: 34rpx;
		}
	}

	.btn-box {
		display: flex;
		justify-content: flex-end;
		

		.order-btn {
      height: 64rpx;
			border-radius: 44rpx;
			padding: 12rpx 32rpx;
			font-size: 28rpx;
			font-weight: 700;
			line-height: 64rpx;
			text-align: center;
      margin-left: 24rpx;
      
			&.cancel {
				background: #F3F6F5;
        color: rgba(0,0,0,0.7);
				margin-left: 24rpx;
			}

			&.pay {
				background: #3FAA73;
				color: #ffffff;
			}

			&.contact {
				position: relative;
				background: #F3F6F5;
				color: rgba(0,0,0,0.7);
				margin-left: 24rpx;
				padding: 12rpx 24rpx 12rpx 35rpx;

				&:before {
					content: "";
					position: absolute;
					left: 24rpx;
					top: 8px;
					display: inline-block;
					width: 40rpx;
					height: 40rpx;
					background: url("../../static/icon-service.png");
					background-repeat: no-repeat;
					background-size: 33.3rpx 33.3rpx;
				}
			}

			&.view {
				background: #ffffff;
				color: #777f8f;
				margin-left: 24rpx;
			}

			&.delete {
				background: #ffffff;
				color: #777f8f;
				margin-left: 24rpx;
			}
		}
	}
</style>